package com.fafu.mq.demo;

import com.fafu.mq.common.Consumer;
import com.fafu.mq.common.MqException;
import com.fafu.mq.mqclient.Channel;
import com.fafu.mq.mqclient.Connection;
import com.fafu.mq.mqclient.ConnectionFactory;
import com.fafu.mq.mqserver.core.BasicProperties;
import com.fafu.mq.mqserver.core.ExchangeType;

import java.io.IOException;

public class DemoConsumer {
    public static void main(String[] args) throws IOException, MqException, InterruptedException {
        System.out.println("启动消费者");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(9090);
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare("testExchange", ExchangeType.DIRECT,true,false,null);
        channel.queueDeclare("testQueue",true,false,false,null);
        channel.basicConsume("testQueue", true, new Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                System.out.println("[消费数据] 开始");
                System.out.println("consumerTag = " + consumerTag);
                System.out.println("basicProperties = " + basicProperties);
                String bodyString = new String(body,0,body.length);
                System.out.println("body = " + bodyString);
                System.out.println("[消费数据] 结束");
            }
        });

        // 由于消费者也不知道生产者会生成多少消息, 所以在这里一直等待
        while (true) {
            Thread.sleep(500);
        }
    }
}
